package com.tiemei.demo.json;

import com.google.gson.Gson;
import static com.tiemei.demo.util.Print.*;

/**
 * Java Object <-> JSON
 * user guide : https://sites.google.com/site/gson/gson-user-guide#TOC-Primitives-Examples
 * 
 * @author tiemei.jdk
 * @date 2012-9-27
 */
public class GsonExamples {

	public static void primitivesExamples() {
		Gson gson = new Gson();
		p(gson.toJson(1)); // 1
		p(gson.toJson("ab/cd")); // "abcd"
		p(gson.toJson(new Long(10))); // 10
		int[] values = { 1 };
		p(gson.toJson(values)); // [1]
	}

	public static void objectExamples() {
		/*
		 * Serialization
		 */
		BagOfPrimitives obj = new BagOfPrimitives();
		Gson gson = new Gson();
		String json = "ni/ni";
		p(json = gson.toJson(obj)); //  {"value1":1,"value2":""}
		
		/*
		 * Deserialization
		 */
		BagOfPrimitives obj2 = gson.fromJson(json, BagOfPrimitives.class);
	}
	static class BagOfPrimitives {
		private int value1 = 1;
		private String value2 = "value/2";
		private transient int value3 = 3;
		private String value4;

		public BagOfPrimitives() {}
	}
	
	public static void arrayExamples() {
		Gson gson = new Gson();
		int[] ints = {1, 2, 3, 4, 5};
		String[] strings = {"abc", "def", "ghi"};
		
		/*
		 *  Serialization
		 */
		p(gson.toJson(ints));     // [1,2,3,4,5]
		p(gson.toJson(strings));  // ["abc", "def", "ghi"]

		/*
		 *  Deserialization
		 */
		int[] ints2 = gson.fromJson("[1,2,3,4,5]", int[].class);  // ints2 will be same as ints
	}
	
	private String f1 = "f1";
	private BagOfPrimitives f2 = new BagOfPrimitives();
	public void beanExample(){
		Gson gson = new Gson();
		p(gson.toJson(new GsonExamples())); // {"f1":"f1","f2":{"value1":1,"value2":"abc"}}
	}
	
	

	public static void main(String args[]) {
		primitivesExamples(); objectExamples(); arrayExamples();
		new GsonExamples().beanExample();
	}
}
